package com.bbm.communitysystem.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.bbm.communitysystem.domain.Comment;
import com.bbm.communitysystem.domain.Post;
import com.bbm.communitysystem.domain.bo.CommentBo;
import com.bbm.communitysystem.domain.dto.post.CommentDto;
import com.bbm.communitysystem.mapper.CommentMapper;
import com.bbm.communitysystem.service.ICommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bbm.communitysystem.service.IPostService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author transitory
 * @since 2025-02-20
 */
@Service
@RequiredArgsConstructor
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements ICommentService {

    private final IPostService postService;
    
    @Override
    @Transactional
    public CommentDto addComment(CommentBo commentBo) {

        Comment comment = BeanUtil.copyProperties(commentBo, Comment.class);
        comment.setCommentLike(0);
        comment.setCreateTime(String.valueOf(System.currentTimeMillis()));

        boolean save = save(comment);

        if (!save) {
            throw new RuntimeException("评论失败");
        }


        boolean update = postService.lambdaUpdate()
                .eq(Post::getId, commentBo.getPostId())
                .setSql("comment = comment + 1")
                .update();

        if (!update) {
            throw new RuntimeException("评论失败");
        }

        return BeanUtil.copyProperties(comment, CommentDto.class);
    }

    @Override
    @Transactional
    public int delComment(CommentBo commentBo) {
        if (commentBo.getId() == null) {
            return 0;
        }

        boolean update = lambdaUpdate()
                .eq(Comment::getId, commentBo.getId())
                .set(Comment::getStatus, 0)
                .update();

        if (!update) {
            throw new RuntimeException("删除失败");
        }

        boolean update1 = postService.lambdaUpdate()
                .eq(Post::getId, commentBo.getPostId())
                .setSql("comment = comment - 1")
                .update();

        if (!update1) {
            throw new RuntimeException("删除失败");
        }

        return 0;
    }



}
